<!-- 冲减 -->
<template>
  <div>
    <el-row class="mt10" type="flex">
      <Search class="mr10" :data="selections" :attribute="'createdTime'" @dateChange="handleDateChange" @change="handleTypeChange" />
      <el-form ref="searchFormRef" :model="searchForm" label-width="100px" :inline="true">
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" @click="writeOffButton">冲减</el-button>-->
        <!--        </el-form-item>-->
      </el-form>
    </el-row>
    <!-- 表单区域 -->
    <el-table v-loading="loading" :data="writeOffList">
      <el-table-column label="冲减单号" prop="offsetOrderNo" />
      <el-table-column label="时间" prop="warehouseOutTime" />
      <el-table-column label="操作人" prop="operator" align="center" />
      <el-table-column label="金额" prop="warehouseOutPrice" align="center" />
      <el-table-column label="操作" min-width="120" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="detailsBtn(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    <!--冲减详情-->
    <Dialog
      :title="title"
      :width="80"
      :visible.sync="detailsVisible"
      :reveal="false"
      :loading="detailsLoading"
      @close="handleClose"
    >
      <div class="headStyle">
        <span>冲减单号：{{ writeOffData.offsetOrderNo }}</span>
        <span>操作人员：{{ writeOffData.operator }}</span>
        <span>操作时间：{{ writeOffData.warehouseOutTime }}</span>
      </div>
      <el-table v-loading="loading" :data="writeOffDetails">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="规格" prop="specs" />
        <el-table-column label="仓库" prop="warehouseName" />
        <el-table-column label="供货商" prop="supplier" />
        <el-table-column label="批次号" prop="batchId" />
        <el-table-column label="到期时间" prop="dueDate" />
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="冲减数量" prop="writeOffCount" />
        <el-table-column label="单价" prop="purchasePrice" />
        <el-table-column label="金额" prop="price" />
      </el-table>
      <span>
        <span><strong>备注：</strong></span>
        <span>{{ writeOffData.remark }}</span>
      </span>
    </Dialog>
    <!-- 冲减 -->
    <Dialog
      :title="title"
      :width="80"
      :visible.sync="visible"
      button-text="确定"
      :loading="loading"
      @close="handleClose"
      @confirm="submitWriteOffForm"
    >
      <p>
        <el-button type="primary" style="width: 25%" @click="addDrugBtn">导入货物</el-button>
      </p>
      <el-table v-loading="loading" :data="goodsList">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="规格" prop="specs" />
        <el-table-column label="进货单价" prop="purchasePrice" />
        <el-table-column label="仓库" prop="warehouseName" />
        <el-table-column label="批次号" prop="batchId" />
        <el-table-column label="库存" prop="stockCount" />
        <el-table-column label="数量" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.writeOffCount" controls-position="right" :min="0" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" min-width="50px" />
        <el-table-column label="到期时间" prop="dueDate" />
        <el-table-column label="供货商" prop="supplier" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form ref="requestFromRef" :model="writeOffInfo">
        <el-form-item>
          <span>
            <span><strong>备注：</strong></span>
            <el-input v-model="writeOffInfo.remark" type="textarea" :autosize="{ minRows:4}" placeholder="请输入内容" class="textareaCss" />
          </span>
        </el-form-item>
      </el-form>
    </Dialog>
    <Dialog
      :title="title"
      :visible.sync="goodsVisible"
      :loading="goodsLoading"
      :button-text="buttonName"
      @close="handleClose"
      @confirm="submitGoodsForm"
    >
      <el-container>
        <el-aside width="195x">
          <LeftClassification @classificationClist="getClassificationId" />
        </el-aside>
        <el-main>
          <span>
            <el-input v-model="searchParams.name" placeholder="请输入名称或者拼音码" clearable style="width: 200px" />
            <el-button type="primary" :loading="searchLoading" @click="searchGoods">搜索</el-button>
          </span>
          <el-table v-loading="loading" :data="addGoodsList" @selection-change="selectionChange">
            <el-table-column label="名称" prop="name" />
            <el-table-column label="规格" prop="spec" />
            <el-table-column label="单位" prop="unit" />
            <el-table-column label="描述" prop="remarks" />
            <el-table-column type="selection" />
          </el-table>
          <pagination :page-num="searchParams.page" :page-size="searchParams.pageSize" :on-change="addGoodsChange" :total="searchTotal" />
        </el-main>
      </el-container>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import LeftClassification from "../../../components/leftClassification";
import { selections } from "@/config";
import Search from "@/components/Search";
export default {
  components: {
    Search,
    Dialog,
    LeftClassification,
  },
  data() {
    return {
      selections,
      searchForm: {},
      writeOffInfo: {},
      searchParams: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      searchTotal: 0,
      options: [],
      writeOffList: [],
      writeOffListData: {},
      goodsList: [],
      selectGoods: [],
      addGoodsList: [],
      warehouseList: [],
      buttonName: '',
      writeOffDetails: [],
      writeOffData: [],
      title: "",
      visible: false,
      goodsVisible: false,
      detailsVisible: false,
      loading: false,
      goodsLoading: false,
      searchLoading: false,
      detailsLoading: false,
      search: {},
    };
  },
  created() {
    this.getWriteOffList();
    this.findAllWarehouse();
  },
  methods: {
    searchChange(e) {
      console.log(e);
    },
    async getWriteOffList() {
      this.loading = true;
      const res = await this.$api['warehouse/writeOff/writeOffList']({ ...this.params, query: this.search });
      this.loading = false;
      if (res.code !== 200) return this.$message.error('查询冲减列表失败！');
      this.writeOffList = res.data.result;
      this.total = res.data.total;
    },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getWriteOffList();
    },
    addGoodsChange(val) {
      this.searchParams = { page: val.pageNum, pageSize: val.pageSize };
      this.searchGoods();
    },
    // 详情
    async detailsBtn(row) {
      this.detailsLoading = true;
      console.log(row);
      const pamars = {
        writeoffId: row.id,
      };
      const res = await this.$api['warehouse/writeOff/writeOffDetails']({ query: pamars });
      if (res.code === 200 && res.data) {
        this.writeOffData = row;
        this.writeOffDetails = res.data.result;
      } else {
        this.writeOffData = {};
        this.writeOffDetails = [];
      }
      this.title = "冲减详情";
      this.detailsVisible = true;
      this.detailsLoading = false;
    },
    // 冲减
    writeOffButton() {
      this.title = "冲减";
      this.goodsList = [];
      this.loading = true;
      this.visible = true;
      this.loading = false;
    },
    // 导入货物
    addDrugBtn() {
      this.title = "选择货物";
      this.buttonName = "已选择（0）";
      this.searchGoods();
      this.goodsVisible = true;
    },
    // 删除货物
    async deleteBtn(row) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      for (var i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].id === row.id) {
          this.goodsList.splice(i, 1);
        }
      }
      this.$message.success('删除货品成功！');
    },
    // 搜索商品
    async searchGoods() {
      this.searchLoading = true;
      const res = await this.$api['warehouse/writeOff/goodsList']({ query: this.searchParams });
      this.searchLoading = false;
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data.result;
      this.searchTotal = res.data.total;
    },
    // 选择商品
    selectionChange(val) {
      console.log(val);
      this.buttonName = "已选择（" + val.length + "）";
      this.selectGoods = val;
    },
    // 提交商品表单
    async submitGoodsForm() {
      console.log("提交表单");
      // 查询提交的货物名字
      this.selectGoods = this.selectGoods.map(v => {
        return v.name;
      });
      const name = this.selectGoods.join(",");
      const pamars = {
        inventoryName: name,
      };
      console.log(pamars);
      this.goodsLoading = true;
      const res = await this.$api['warehouse/writeOff/findInventory']({ query: pamars });
      this.goodsLoading = false;
      if (res.code !== 200) return this.$message.error('查询商品列表失败！');
      if (res.data.result.length === 0) return this.$message.error('所选商品还没有库存！');
      // 先删除重复的货物
      for (var i = 0; i < this.goodsList.length; i++) {
        for (var j = 0; j < res.data.result.length; j++) {
          if (this.goodsList[i].id === res.data.result[j].id) {
            res.data.result.splice(j, 1);
          }
        }
      }
      this.goodsList.push(...res.data.result);
      this.goodsList.filter(item => {
        item.name = item.inventoryName;
        item.specs = item.inventorySpecl;
        item.batchId = item.inventoryBatch;
        item.dueDate = item.inventoryExpiredDate;
        item.supplier = item.inventorySupplier;
        item.unit = item.inventoryUnit;
        item.inventoryId = item.id;
      });
      this.selectGoods = [];
      this.goodsVisible = false;
    },
    // 提交冲减表单
    async submitWriteOffForm() {
      console.log("提交冲减表单");
      // 添加仓库名称
      for (var i = 0; i < this.goodsList.length; i++) {
        for (var j = 0; j < this.warehouseList.length; j++) {
          if (this.goodsList[i].warehouseId === this.warehouseList[j].id) {
            this.goodsList[i].warehouseName = this.warehouseList[j].name;
          }
        }
      }
      console.log(this.goodsList);
      console.log(this.writeOffInfo);
      if (this.goodsList.length === 0) return this.$message.error('冲减商品不能为空！');
      this.loading = true;
      const res = await this.$api['warehouse/writeOff/writeOff']({ listDto: this.goodsList, ...this.writeOffInfo });
      this.loading = false;
      this.visible = false;
      this.goodsList = [];
      if (res.code !== 200) return this.$message.error('添加冲减失败！');
      this.$message.success('添加冲减成功！');
      this.getWriteOffList();
    },
    // 获取库房列表
    async findAllWarehouse() {
      this.loading = true;
      const res = await this.$api['warehouse/writeOff/allWarehouse']();
      this.loading = false;
      if (res.code !== 200) return this.$message.error('获取仓库列表失败！');
      this.warehouseList = res.data;
    },
    // 获取产品分类id
    async getClassificationId(val) {
      console.log(val);
      // 查询提交的产品分类id
      this.searchParams.productClassificationId = val.list.join(",");
      const res = await this.$api['warehouse/stock/goodsList']({ query: this.searchParams });
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data.result;
      this.searchTotal = res.data.total;
    },
    // 关闭
    handleClose() {
      this.searchLoading = false;
      this.loading = false;
      this.goodsLoading = false;
      // this.$refs.ruleForm.resetFields();
    },
    handleDateChange(val) {
      Object.assign(this.search, val);
      this.getWriteOffList();
    },
    handleTypeChange(val) {
      Object.assign(this.search, val);
      this.getWriteOffList();
    },
  },
};
</script>
<style lang="scss" scoped>
  .headStyle.fofo {
    padding-top: 15px;
    margin-top: 15px;
    border-top: 1px dashed #eee !important;
  }
  .el-steps {
    justify-content: center;
  }
  .el-aside {
    background: #fff;
  }
</style>

